<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class UserPointsLog extends Model
{
    protected function getOptions(): array
    {
        return [
            'autoWriteTimestamp' => true,
            'createTime'         => 'create_time',
            'updateTime'         => false,
            'jsonAssoc'          => true,
        ];
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }

    /**
     * 获取积分类型列表
     * @return array
     */
    public static function getPointsTypes()
    {
        return [
            'register'          => '注册奖励',
            'sign'              => '签到奖励',
            'purchase'          => '购买商品',
            'comment'           => '发表评论',
            'comment_liked'     => '评论被点赞',
            'content_favorited' => '内容被收藏',
            'profile_complete'  => '完善资料',
            'bind_mobile'       => '绑定手机',
            'first_recharge'    => '首次充值',
            'invite_user'       => '邀请用户',
            'exchange'          => '积分兑换',
            'admin_adjust'      => '管理员调整',
            'vip_purchase'      => '购买VIP',
            'task_reward'       => '任务奖励',
        ];
    }

    /**
     * 获取用户积分记录
     * @param int $userId 用户ID
     * @param string $type 积分类型，为空则获取所有类型
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public static function getUserPointsLogs($userId, $type = '', $page = 1, $limit = 10)
    {
        $query = self::where('user_id', $userId);

        if (!empty($type)) {
            $query->where('type', $type);
        }

        $total = $query->count();

        $logs = $query->order('create_time', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();

        return [
            'total' => $total,
            'data'  => $logs,
        ];
    }

    /**
     * 获取用户积分统计
     * @param int $userId 用户ID
     * @return array
     */
    public static function getUserPointsStats($userId)
    {
        // 总收入积分
        $totalIncome = self::where('user_id', $userId)
            ->where('points', '>', 0)
            ->sum('points');

        // 总支出积分
        $totalExpense = self::where('user_id', $userId)
            ->where('points', '<', 0)
            ->sum('points');

        // 按类型统计
        $types     = self::getPointsTypes();
        $typeStats = [];

        foreach ($types as $key => $name) {
            $income = self::where('user_id', $userId)
                ->where('type', $key)
                ->where('points', '>', 0)
                ->sum('points');

            $expense = self::where('user_id', $userId)
                ->where('type', $key)
                ->where('points', '<', 0)
                ->sum('points');

            $typeStats[$key] = [
                'name'    => $name,
                'income'  => $income,
                'expense' => $expense,
                'balance' => $income + $expense,
            ];
        }

        return [
            'total_income'  => $totalIncome,
            'total_expense' => $totalExpense,
            'balance'       => $totalIncome + $totalExpense,
            'type_stats'    => $typeStats,
        ];
    }
}